﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// 一个UI模型
/// </summary>
public class UIModel
{
    // 摄影棚根节点
    GameObject _studioRoot;
    // 模型位置
    Transform _modelPlace;
    // 摄像机
    Camera _modelCamera;
    // 渲染目标
    RenderTexture _modelTexture;
    // UI展示
    RawImage _modelImage;

    public float RotateSpeed = 0.7f;

    public UIModel(int width, int height, RawImage modelImage, GameObject model)
    {
        _modelImage = modelImage;
        _studioRoot = ResMgr.instance.InstanceGameObject("UI/UIModel/UIModeStudio");
        _modelPlace = _studioRoot.FindComponent<Transform>("House/ModePlace");
        _modelCamera = _studioRoot.FindComponent<Camera>("Camera");
        _modelTexture = new RenderTexture(Mathf.FloorToInt(width), Mathf.FloorToInt(height), 16);
        _modelImage.texture = _modelTexture;
        _modelCamera.targetTexture = _modelTexture;

        model.transform.SetParent(_modelPlace, false);

        // 触摸旋转
        var touch = modelImage.gameObject.AddComponent<TouchEx>();
        touch.OnDragCallback = onTouchModel;
    }

    public void Release()
    {
        _modelTexture = null;
        _modelImage.texture = null;
        GameObject.Destroy(_studioRoot);
    }

    public void SetRootPosition(Vector3 pos)
    {
        _studioRoot.transform.position = pos;
    }

    /// <summary>
    /// 拖动事件响应
    /// </summary>
    private void onTouchModel(PointerEventData data)
    {
        _modelPlace.Rotate(0, -data.delta.x * RotateSpeed, 0);
    }
}
